<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.name" clearable size="small" placeholder="输入分类名称搜索" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!--表单组件-->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="form.name" style="width: 370px;" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" style="width: 370px;" />
        </el-form-item>
        <el-form-item style="margin-bottom: 0;"<el-form-item label="上级分类" prop="pid">
          <treeselect v-model="form.pid" :options="depts" :normalizer="normalizer" style="width: 370px;" placeholder="选择上级分类" />
        </el-form-item>
        <el-form-item label="分类图标">
          <div class="avatar-uploader">
            <el-upload
              class="avatar-uploader"
              action="/admin/upload-product-material"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="{Authorization: `Bearer ${this.getToken()}`}"
            >
              <img v-if="form.icon" :src="form.icon" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table ref="table" v-loading="crud.loading" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" :data="crud.data" row-key="id" @select="crud.selectChange" @select-all="crud.selectAllChange" @selection-change="crud.selectionChangeHandler">
      <el-table-column :selectable="checkboxT" type="selection" width="55" />
      <el-table-column v-if="columns.visible('name')" label="名称" prop="name" />
      <el-table-column v-if="columns.visible('sort')" label="排序" prop="sort" sortable/>
      <el-table-column v-permission="['admin','YXSTORECATEGORY_EDIT','YXSTORECATEGORY_DELETE']" label="操作" width="130px" align="center" fixed="right">
        <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :permission="permission"
            :disabled-dle="scope.row.id === 1"
            msg="确定删除吗,如果存在下级节点则一并删除，此操作不能撤销！"
          />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import crudDept from '@/api/product/category'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation.vue'
import crudOperation from '@crud/CRUD.operation.vue'
import udOperation from '@crud/UD.operation.vue'
import { getToken as getAuthToken } from '@/utils/auth'

// crud交由presenter持有
const defaultCrud = CRUD({ title: '分类', url: 'admin/get-category-list', sort: 'sort,desc', crudMethod: { ...crudDept }})
const defaultForm = { id: null, name: null, pid: 0, sort:  1, icon: ''}
export default {
  name: 'ProductCategory',
  components: { Treeselect, crudOperation, rrOperation, udOperation },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      normalizer(node){
	        //去掉children=[]的children属性 respectively
	        if(node.children && !node.children.length){
	          delete node.children;
	        }
      },
      picArr: [],
      depts: [],
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      permission: {
        add: ['admin', 'cate:add'],
        edit: ['admin', 'cate:edit'],
        del: ['admin', 'cate:del']
      },
      enabledTypeOptions: [
        { key: 'true', display_name: '正常' },
        { key: 'false', display_name: '禁用' }
      ]
    }
  },
  watch: {
  },
  methods: {
    getToken() {
      return getAuthToken()
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.picArr = []
      if (form.pic && form.id) {
        this.picArr = form.pic.split(',')
      }
      // 初始化图标
      if (form.icon && form.id) {
        this.form.icon = form.icon
      } else {
        this.form.icon = ''
      }

      // 获取所有类目
      crudDept.getList().then(res => {
        this.depts = []
        const dept = { id: 0, label: '顶级类目', children: [] }
        dept.children = res.data
        this.depts.push(dept)
      })
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU]() {
      return true
    },
    handleAvatarSuccess(res) {
      this.form.icon = res.data.image_path
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },
    checkboxT(row, rowIndex) {
      return row.id !== 1
    }
  }
}
</script>

<style scoped>
.avatar-uploader {
  display: flex;
  align-items: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 36px;
  color: #409EFF;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  background-color: #f5f7fa;
  border-radius: 50%;
  transition: all 0.3s ease;
}
.avatar-uploader-icon:hover {
  color: #67c23a;
  transform: scale(1.05);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
  object-fit: cover;
}
</style>
